import { access } from 'fs/promises';
import fs from 'fs';
import got, { Progress } from 'got';
import path from 'path';
import { cwd } from 'process';
import { Buffer } from 'buffer';
import { IncomingMessage } from 'http';
import { getFileSize } from './utils';
import ProgressBar from 'progress';
import {mergeConfig} from './config'

const softwarePath = path.join(cwd(), 'softwarePath');

/**
 * 创建软件目录
 * @return {String} outDir
 */
const createSoftDir = async (outDir?: string) => {
  try {
    await access(outDir? outDir: softwarePath);
    return true;
  } catch (error) {
    console.log('目录不存在， 直接创建');

    fs.mkdirSync(outDir? outDir: softwarePath);

    return true;
  }
};

const singleFile = (file:Software.IFileMap) => {
  let stream = fs.createWriteStream(
    path.join(softwarePath, `${file.name}.exe`)
  );

  let readStream = got.stream.get(file.url);

  let bar:ProgressBar

  readStream.on('response', (response: IncomingMessage) => {
    let headers = response.headers;

    let total: number = Number(headers['content-length']);

    console.log('文件大小', getFileSize(headers['content-length']!));
    console.log('\n')

    // size = getFileSize(headers['content-length']!)

    // fs.writeFile('./1.json', JSON.stringify(headers, null, 4), (err) => {
    //   if(err) {
    //     console.log('写入响应体失败')
    //     console.log(err)
    //   }

    // })

   bar = new ProgressBar('[:bar] :percent', {
      total: total || 0,
      curr: 0,
      incomplete: ' ',
      width: 100
    });
  });

  readStream.on('data', chunk => {
    bar.tick(chunk.length)
  })

  // https://github.com/sindresorhus/got/blob/HEAD/documentation/3-streams.md#response-1
  // readStream.on('downloadProgress', (res: Progress) => {
  // });

  readStream.pipe(stream).on('close', (err: any) => {
    if (err) {
      console.log('下载失败');
      console.log(err);
      return;
    }

    console.log('下载完成');
  });
}

const resolveFiles = async() => {
  let all:boolean = mergeConfig().all;
  let list:Array<Software.IFileMap> = mergeConfig().list

  list.forEach(file => singleFile(file))
}

const start = async (outDir?:string) => {
  try {
    let hasSoftPath = await createSoftDir(outDir);

    if (!hasSoftPath) return;

    resolveFiles()
  } catch(e) {
    console.log('start报错')
    console.log(e)
  }
};


start();
